package com.thzy.bbs.common;

import java.security.MessageDigest;

/**
 * Java标准加密工具类
 *
 * @author Ziv
 * @version 2.0.0
 * @since 2016/11/04 test:16
 */
public class EncodeUtils {

    /**
     * 各个加密算法的名称
     */
    private static final String MD5 = "MD5";

    /**
     * MD5加密
     *
     * @param str 加密原串
     * @return MD5加密后字符串
     * @author Ziv
     */
    public static String encodeMD5(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        } else {
            return encode(MD5, str);
        }
    }

    private static String encode(String algorithm, String str) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(str.getBytes());
            return convertBytesToHexStr(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将给定的字节序列转换为十六进制字符串表示[8bit -> 2hex]
     *
     * @param binaryArray
     * @return java.lang.String
     */
    public static String convertBytesToHexStr(byte[] binaryArray) {
        StringBuilder encodeString = new StringBuilder();
        for (byte binary : binaryArray) {
            String hex = Integer.toHexString(binary & 0XFF);
            encodeString.append((hex.length() == 1 ? "0" + hex : hex));
        }
        return encodeString.toString();
    }


}
